package com.sgb.net.core;

import com.sgb.net.BuildConfig;


import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author: 杨畔
 * @date: 2021/2/19 14:48
 * @Description: 网络请求封装基类
 */
public abstract class BaseNet implements NetInterface {
    protected OkHttpClient mClient;
    protected String mBaseUrl = NetConfig.mBaseUrl;

    public BaseNet() {
        initNet();
    }

    @Override
    public void initNet() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //判断是否有自定义拦截器
        if (!NetConfig.mInterceptors.isEmpty()) {
            for (Interceptor interceptor : NetConfig.mInterceptors) {
                builder.addInterceptor(interceptor);
            }
        }
        //日志打印
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }
        //通用配置
        builder.addInterceptor(new UrlInterceptor(1))
                .addInterceptor(logging)
                .readTimeout(NetConfig.mTimeOut, TimeUnit.SECONDS)
                .writeTimeout(NetConfig.mTimeOut, TimeUnit.SECONDS)
                .connectTimeout(NetConfig.mTimeOut, TimeUnit.SECONDS);
        handleBuilder(builder);
        mClient = builder.build();
    }

    /**
     * 网络请求扩展
     */
    protected abstract void handleBuilder(OkHttpClient.Builder builder);

    @Override
    public <S> S getService(Class<S> serviceClass, String baseUrl) {
        return new Retrofit.Builder()
                .client(mClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build()
                .create(serviceClass);
    }
}
